package com.cloud.dataway.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Slf4j
public class DBRoutingInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method paramMethod = invocation.getMethod();
        String methodName = paramMethod.getName();


        DBRouting anno = paramMethod.getAnnotation(DBRouting.class);
        if (anno == null) {
            anno = paramMethod.getDeclaringClass().getAnnotation(DBRouting.class);
            if (anno == null) {
                if (log.isDebugEnabled() && !paramMethod.getDeclaringClass().getName().startsWith("com.fasterxml.jackson.databind.ObjectMapper")) {
                    log.debug("### DBExchangeInterceptor: method = " + paramMethod.getDeclaringClass().getName() + "."
                            + methodName + ", DataSource = " + DbContextHolder.getDbType());
                }
                return invocation.proceed();
            }
        }
        DbContextHolder.DataSource target = anno.target();

        String targetDB = target.getText();
        if (StringUtils.isEmpty(targetDB)) {
            targetDB = DbContextHolder.DataSource.MASTER.getText();
        }
        DbContextHolder.setDbType(targetDB);

        if (log.isDebugEnabled()) {
            log.debug("### DBExchangeInterceptor: method = " + paramMethod.getDeclaringClass().getName() + "."
                    + methodName + ", DataSource = " + DbContextHolder.getDbType());
        }

        try {
            return invocation.proceed();
        } finally {
            DbContextHolder.setDbType(DbContextHolder.DataSource.MASTER.getText());
        }
    }
}
